import {messages} from "share/common";
/**
 * Created by fudebao on 2017/12/05.
 */
import React from 'react';
import { connect } from 'react-redux';
import { Button, Form, Switch, Spin, message, Select } from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
import companyAccountSettingService from './company-account-setting.service'

class AddPayWay extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      params: {},
      loading: false,
      companyTypeList: [],
      setOfBooksNameList: [],
      legalEntityList: [],
      companyLevelList: [],
      parentCompanyList: [],
      dateFormat: 'YYYY/MM/DD',
      payWayTypeList: [],
      payWayList: [],
      disabled: true,
      flag: true,
      isOn: 'inline',
      selectLoading: false,
      selectLoad: false,
      spinLoad: false
    };
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.params.flag && !this.props.params.flag) {
      this.props.form.resetFields();
      let record = nextProps.params.record;
      if (record.id) {
        this.setState({ params: nextProps.params.record, disabled: false, isOn: nextProps.params.record.isDefault ? 'none' : 'inline', spinLoad: true}, () => {
          Promise.all([
            this.getPayWayList(nextProps.params.record.paymentMethodCategory),
            this.getPayWayTypeList()
          ]).then(() => {
            this.setState({spinLoad: false});
          })
        });
      }
      else {
        this.setState({ params: nextProps.params.record });
        this.getPayWayTypeList();
      }
    }
  }
  //获取付款方式类型
  getPayWayTypeList = () => {
    this.setState({selectLoading: true});
    this.getSystemValueList(2105).then(res => {
      this.setState({ payWayTypeList: res.data.values, selectLoading: false });
    })
  };

  //获取付款方式
  getPayWayList = (type) => {
    let params = this.state.params;
    let temp1 = params.id ? "&companyPaymentId=" + params.id : "";
    let temp2 = params.id ? "&paymentMethodId=" + params.paymentMethodId : "";
    this.setState({selectLoad:true});
    companyAccountSettingService.getPayWayList(params.companyBankId,type,temp1,temp2).then(res => {
      this.setState({ payWayList: res.data,selectLoad: false });
    })
  }

  //付款类型改变时触发
  typeChange = (value) => {

    value ? this.setState({ disabled: false }) : this.setState({ disabled: true });

    this.props.form.setFieldsValue({
      paymentMethodId: []
    });

    this.getPayWayList(value);
  }

  //编辑保存
  handleSave = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { isOn } = this.state;
        this.setState({ loading: true });
        let temp = {};
        if (this.state.params.id) {
          temp = { id: this.state.params.id, paymentMethodId: values.paymentMethodId, bankAccountId: this.state.params.companyBankId, defaults: (isOn === 'none' ? true : false)};
        }
        else {
          temp = { paymentMethodId: values.paymentMethodId, bankAccountId: this.state.params.companyBankId, defaults: (isOn === 'none' ? true : false)};
        }

        companyAccountSettingService.savePayWay(temp).then((res) => {
          this.setState({ loading: false });
          this.props.form.resetFields();
          this.props.close(true);
          message.success(messages('common.operate.success'));
        }).catch((e) => {
          this.setState({ loading: false });
          message.error(e.response.data.message);
        })
      }
    });
  };

  onCancel = () => {
    this.props.close();
  };

  handleChangeSwitch = (value) => {
    this.setState({isOn : value ? 'none' : 'inline'})
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { params, payWayTypeList, payWayList, disabled, selectLoading, selectLoad, spinLoad } = this.state;
    const formItemLayout = {
      labelCol: { span: 6, offset: 1 },
      wrapperCol: { span: 14, offset: 1 },
    };
    return (
      <div className="new-payment-method">
        <Spin spinning={spinLoad}>
        <Form>
          <FormItem {...formItemLayout} label={messages('pay-setting.key21'/*付款方式类型*/)}>
            {getFieldDecorator('payWayType', {
              rules: [{
                required: true,
                message: messages('common.please.enter')
              }],
              initialValue: params.id ? params.paymentMethodCategory : ""
            })(
              <Select onChange={this.typeChange}
                      notFoundContent={selectLoading ? <Spin size="small" /> : messages('loan-billing.key82')/*无匹配结果*/}
                      placeholder={messages('common.please.select')}>
                {payWayTypeList.map(option => {
                  return <Option key={option.code}>{option.messageKey}</Option>
                })}
              </Select>)}
          </FormItem>

          <FormItem {...formItemLayout} label={messages('pay-setting.key22'/*付款方式*/)}>
            {getFieldDecorator('paymentMethodId', {
              rules: [{
                required: true,
                message: messages('common.please.enter')
              }],
              initialValue: params.id ? params.paymentMethodId : []
            })(
              <Select disabled={disabled}
                      notFoundContent={selectLoad? <Spin size="small" /> : messages('loan-billing.key82')/*无匹配结果*/}
                      placeholder={messages('common.please.select')}>
                {payWayList.map(option => {
                  return <Option key={option.id}>{option.description}</Option>
                })}
              </Select>)}
          </FormItem>

          <FormItem {...formItemLayout} label={messages('pay-setting.key69')/*设为默认*/}>
            {getFieldDecorator('defaults', {
              valuePropName: 'checked',
              initialValue: params.id ? params.isDefault : false
            })(
              <Switch onChange={this.handleChangeSwitch}/>
            )}
          </FormItem>
          <span style={{position:'absolute',left:'300px',top:'133px'}}>{messages('pay-setting.key71')/*（仅能存在一个默认）*/}</span>
        </Form>
        </Spin>
        <div className="slide-footer">
          <Button type="primary" onClick={this.handleSave}
                  loading={this.state.loading}>{messages('common.save')}</Button>
          <Button onClick={this.onCancel}>{messages('common.cancel')}</Button>
        </div>
      </div>
    )
  }
}



const WrappedNewSubjectSheet = Form.create()(AddPayWay);
function mapStateToProps(state) {
  return {
    company: state.login.company,
  }
}
export default connect(mapStateToProps)(WrappedNewSubjectSheet);
